package com.team.arms.bingyiInfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team.arms.bingyiInfo.entity.BingyiInfo;
import com.team.arms.bingyiInfo.entity.dto.BingyiInfoDTO;
import com.team.arms.bingyiInfo.entity.dto.ConditionDTO;
import com.team.arms.bingyiInfo.entity.vo.BingyiInfoVO;
import com.team.arms.bingyiInfo.mapper.BingyiInfoMapper;
import com.team.arms.bingyiInfo.service.IBingyiInfoService;
import com.team.arms.common.Result;
import com.team.arms.common.error.BusinessException;
import com.team.arms.common.ry.utils.StringUtils;
import com.team.arms.political.domain.PoliReviewInfo;
import com.team.arms.political.mapper.PoliReviewInfoMapper;
import com.team.arms.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WY
 * @since 2022-05-04
 */
@Service
public class BingyiInfoServiceImpl extends ServiceImpl<BingyiInfoMapper, BingyiInfo> implements IBingyiInfoService {
    @Autowired
    BingyiInfoMapper bingyiInfoMapper;

    @Autowired
    PoliReviewInfoMapper politicalReviewInformationMapper;
    
    @Override
    public int insertBingyiInfo(BingyiInfoDTO bingyiInfoDTO) {
        System.out.println(bingyiInfoDTO.toString());
        BingyiInfo bingyiInfo=new BingyiInfo(bingyiInfoDTO.getName(),bingyiInfoDTO.getSex(),bingyiInfoDTO.getIdCard(),bingyiInfoDTO.getBeforeName(),bingyiInfoDTO.getBirthday(),bingyiInfoDTO.getNation(),bingyiInfoDTO.getIsRegister(),bingyiInfoDTO.getEducation(),bingyiInfoDTO.getMarriageCondition(),bingyiInfoDTO.getCreateBy(),bingyiInfoDTO.getAge(),bingyiInfoDTO.getDomicileProvince(),bingyiInfoDTO.getDomicileCity(),bingyiInfoDTO.getDomicileDistrict(),bingyiInfoDTO.getDomicileTown(),bingyiInfoDTO.getNativeProvince(),bingyiInfoDTO.getNativeTown(),bingyiInfoDTO.getNativeDistinct());
        int insert = bingyiInfoMapper.insert(bingyiInfo);//用于获得主键id
        if (insert!=0){
            System.out.println(bingyiInfo.toString());
            PoliReviewInfo politicalReviewInformation=new PoliReviewInfo();
            politicalReviewInformation.setBingyiInfoId(bingyiInfo.getBingyiInfoId());
            politicalReviewInformation.setPoliStatus(bingyiInfoDTO.getPoliStatus());
            politicalReviewInformationMapper.insert(politicalReviewInformation);//此时获得政审id

            bingyiInfo.setZPoliticalInfoId(politicalReviewInformation.getPoliInfoId());
            bingyiInfoMapper.updateById(bingyiInfo);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public int updateBinyiInfo(BingyiInfoDTO bingyiInfoDTO) {
        BingyiInfo bingyiInfo=new BingyiInfo(bingyiInfoDTO.getBingyiInfoId(),bingyiInfoDTO.getName(),bingyiInfoDTO.getSex(),bingyiInfoDTO.getIdCard(),bingyiInfoDTO.getBeforeName(),bingyiInfoDTO.getBirthday(),bingyiInfoDTO.getNation(),bingyiInfoDTO.getIsRegister(),bingyiInfoDTO.getEducation(),bingyiInfoDTO.getMarriageCondition(),bingyiInfoDTO.getCreateBy(),bingyiInfoDTO.getAge(),bingyiInfoDTO.getDomicileProvince(),bingyiInfoDTO.getDomicileCity(),bingyiInfoDTO.getDomicileDistrict(),bingyiInfoDTO.getDomicileTown(),bingyiInfoDTO.getNativeProvince(),bingyiInfoDTO.getNativeTown(),bingyiInfoDTO.getNativeDistinct());
        bingyiInfoMapper.updateById(bingyiInfo);

        QueryWrapper<BingyiInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("bingyi_info_id",bingyiInfoDTO.getBingyiInfoId())
                .select("z_political_info_id")
                .last("limit 1");
        BingyiInfo bingyiInfoOld = bingyiInfoMapper.selectOne(queryWrapper);

        //更新政治面貌
        QueryWrapper<PoliReviewInfo> queryWrapperPolitical=new QueryWrapper<>();
        queryWrapperPolitical.eq("poli_info_id",bingyiInfoOld.getZPoliticalInfoId()).last("limit 1");
        PoliReviewInfo politicalReviewInformation = politicalReviewInformationMapper.selectOne(queryWrapperPolitical);
        if (politicalReviewInformation!=null){
            politicalReviewInformation.setPoliStatus(bingyiInfoDTO.getPoliStatus());
            politicalReviewInformationMapper.updateById(politicalReviewInformation);
        }else{
            System.out.println("政审信息中没有对应的兵役id");
        }

        return 1;
    }

    @Override
    public List<BingyiInfoVO> selectBingyiInfo(ConditionDTO[] conditionDTO) {
        //首先第一个条件是姓名(可以不用有connectWord) 可以选择模糊查询或者精确查询
        QueryWrapper<BingyiInfo> queryWrapperBingyi=new QueryWrapper<>();


        //一共有四种可能
        //传入and and: A and B and C
        //传入or and: (A and C ) or B
        //传入and or:  (A and B) or C
        //传入or or:

        if((conditionDTO[1].getConnectWord().equals("and")&&conditionDTO[2].getConnectWord().equals("or"))||(conditionDTO[1].getConnectWord().equals("or")&&conditionDTO[2].getConnectWord().equals("and"))){
            //这里既有or 又有and的情况
            if(conditionDTO[1].getConnectWord().equals("and")){
                //C or (A and B)
                queryWrapperBingyi.lambda()
                        .like(BingyiInfo::getAge,conditionDTO)
                        .or(wp->wp.eq(BingyiInfo::getName,conditionDTO[0].getContext())).eq(BingyiInfo::getIdCard,conditionDTO[1].getContext());
            }else{
                //B or (A and C )
                queryWrapperBingyi.lambda()
                        .like(BingyiInfo::getIdCard,conditionDTO[1].getContext())
                        .or(wp->wp.eq(BingyiInfo::getName,conditionDTO[0].getContext())).eq(BingyiInfo::getAge,conditionDTO[2].getContext());
            }
        }else{
            //正常传参
            if(conditionDTO[0].getIsExact().equals("1")){
                queryWrapperBingyi.eq("name",conditionDTO[0].getContext());
            }else{
                queryWrapperBingyi.like("name",conditionDTO[0].getContext());
            }


            //第二个条件
            if(conditionDTO[1].getConnectWord().equals("and")){
                queryWrapperBingyi.like("id_card",conditionDTO[1].getContext());
            }else if(conditionDTO[1].getConnectWord().equals("or")){
                queryWrapperBingyi.or().like("id_card",conditionDTO[1].getContext());
            }else{
                queryWrapperBingyi.notIn("id_card",conditionDTO[1].getContext());
            }

            //第三个条件
            if(conditionDTO[2].getConnectWord().equals("and")){
                queryWrapperBingyi.eq("age",conditionDTO[2].getContext());
            }else if(conditionDTO[2].getConnectWord().equals("or")){
                queryWrapperBingyi.or().eq("age",conditionDTO[2].getContext());
            }else{
                queryWrapperBingyi.notIn("age",conditionDTO[2].getContext());
            }
        }

        List<BingyiInfo> bingyiInfos = bingyiInfoMapper.selectList(queryWrapperBingyi);
        List<BingyiInfoVO> bingyiInfoVOS=new ArrayList<>();
        for (BingyiInfo bingyiInfo : bingyiInfos){
            //获取政治面貌
            QueryWrapper<PoliReviewInfo> queryWrapperPolitical=new QueryWrapper<>();
            queryWrapperPolitical.eq("poli_info_id",bingyiInfo.getZPoliticalInfoId())
                    .select("poli_status")
                    .last("limit 1");
            PoliReviewInfo poliReviewInfo = politicalReviewInformationMapper.selectOne(queryWrapperPolitical);
            if (poliReviewInfo==null){
                poliReviewInfo=new PoliReviewInfo();
            }
            BingyiInfoVO bingyiInfoVO=new BingyiInfoVO(bingyiInfo.getBingyiInfoId(),bingyiInfo.getName(),bingyiInfo.getSex(),bingyiInfo.getIdCard(),bingyiInfo.getBeforeName(),bingyiInfo.getBirthday(),bingyiInfo.getAge(),bingyiInfo.getNation(),bingyiInfo.getIsRegister(),poliReviewInfo.getPoliStatus(),bingyiInfo.getEducation(),bingyiInfo.getMarriageCondition());
             bingyiInfoVOS.add(bingyiInfoVO);

        }
        bingyiInfoVOS.forEach(System.out::println);
        return bingyiInfoVOS;
    }

    @Override
    public List<BingyiInfoVO> selectBingyiInfoList(BingyiInfoVO bingyiInfo) {
        return bingyiInfoMapper.selectBingyiInfoList(bingyiInfo);
    }

    /**
     * 导入学生数据
     *
     * @param bingyiInfoList  学生数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     *                      operName 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importStudent(List<BingyiInfo> bingyiInfoList, Boolean updateSupport) {
        if (StringUtils.isNull(bingyiInfoList) || bingyiInfoList.size() == 0)
        {
            System.out.println("多少有点导入失败的问题");
//            throw new BusinessException();
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BingyiInfo bingyiInfo : bingyiInfoList)
        {
            try
            {
                // 验证是否存在这个用户
                QueryWrapper<BingyiInfo> queryWrapperBingyiInfo = new QueryWrapper<BingyiInfo>();
                queryWrapperBingyiInfo.eq("bingyi_info_id",bingyiInfo.getBingyiInfoId()).last("limit 1");
                BingyiInfo u = bingyiInfoMapper.selectOne(queryWrapperBingyiInfo);
                System.out.print(bingyiInfo.getSex()+"");
                if (StringUtils.isNull(u))
                {
                    bingyiInfo.setName(bingyiInfo.getName());
                    bingyiInfoMapper.insertBingyiInfo(bingyiInfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "兵役信息" + bingyiInfo.getName() + " 导入成功");
                }
                else if (updateSupport)
                {
//                    bingyiInfo.setUpdateBy(operName);
                    bingyiInfoMapper.updateById(bingyiInfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "兵役信息 " + bingyiInfo.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "兵役信息" + bingyiInfo.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "兵役信息" + bingyiInfo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            System.out.println(failureMsg.toString());
//            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String selectPoliticalStatusByBingyiId(String BingyiId) {
        QueryWrapper<BingyiInfo> queryWrapperBingyi=new QueryWrapper<>();
        queryWrapperBingyi.eq("bingyi_info_id",BingyiId)
                .select("z_political_info_id");
        BingyiInfo bingyiInfo = bingyiInfoMapper.selectOne(queryWrapperBingyi);

        //获取政治面貌
        QueryWrapper<PoliReviewInfo> queryWrapperPolitical=new QueryWrapper<>();
        queryWrapperPolitical.eq("poli_info_id",bingyiInfo.getZPoliticalInfoId())
                .select("poli_status")
                .last("limit 1");
        PoliReviewInfo poliReviewInfo = politicalReviewInformationMapper.selectOne(queryWrapperPolitical);
        if (poliReviewInfo==null){
            poliReviewInfo=new PoliReviewInfo();
        }
        return poliReviewInfo.getPoliStatus();
    }

    @Override
    public Result importExcel(MultipartFile file) {
        //获取文件名
        String filename = file.getOriginalFilename();
        String pattern = filename.substring(filename.lastIndexOf(".") + 1);
        List<List<String>> listContent = new ArrayList<>();
        if (file != null) {
            if (!ExcelUtil.isExcel(file)) {
                return Result.error("导入失败，该文件不是excel文件");
            }
            listContent = ExcelUtil.readExcelContents(file, pattern);
            if (listContent.isEmpty()) {
                return Result.error("表格为空");
            }
            for (int i = 0; i < listContent.size(); i++) {
//                String dateStr = listContent.get(i).get(5);
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter);
//                System.out.println(parsedDate);

                BingyiInfo bingyiInfo=new BingyiInfo();
                bingyiInfo.setName(listContent.get(i).get(1));
                bingyiInfo.setSex(listContent.get(i).get(2));
                bingyiInfo.setIdCard(listContent.get(i).get(3));
                bingyiInfo.setBeforeName(listContent.get(i).get(4));
//                bingyiInfo.setBirthday(parsedDate);
                bingyiInfo.setAge(listContent.get(i).get(6));
                bingyiInfo.setNation(listContent.get(i).get(7));
                bingyiInfo.setZPoliticalInfoId(listContent.get(i).get(10));
                bingyiInfo.setEducation(listContent.get(i).get(11));
                bingyiInfo.setMarriageCondition(listContent.get(i).get(12));
                //存入数据库
                this.save(bingyiInfo);
            }
            return Result.success(listContent);
        }
        return Result.error("未选择文件");
    }
}

